$(function () {

    let userid = getCookie("userid");
    let token = getCookie("token");
    let title = $(".nick")
    let userinfo = $(".ready")
    let logout = $(".logout")
    function init() {
        if (userid && token) {
            loadUserMsg(userid, token)
                .done(function (res) {

                    renderUserMsg(res)

                })
        }
    }

    function loadUserMsg(id, token) {

        let options = {

            url: "http://127.0.0.1:8888/users/info/" + id,
            type: "GET",
            headers: {
                authorization: token
            },
            dataType: "json"
        }

        return $.ajax(options)

    }

    function renderUserMsg(data) {

        title.html(`${data.info.nickname}`);
        userinfo.html(`已登陆`)

    }

    //注销登陆
    logout.click(function () {

        let userid = getCookie("userid");
        let token = getCookie("token");
        if (userid && token) {
            logoutUser(userid, token)
                .done(function (data) {

                    if (data.code === 1) {
                        // 成功注销之后， 我们刷新页面即可; 
                        removeCookie("userid");
                        removeCookie("token");
                        location.reload();
                        alert("退出登陆成功")
                    }

                })
        }else{

            alert("您还没有登录,请先登录")

        }
    })

    function logoutUser(id , token) {

        let options = {

            url: "http://127.0.0.1:8888/users/logout/" + id,
            type: "GET",
            headers: {
                authorization: token
            },
            dataType: "json"

        }
        return $.ajax(options)

    }
    init()

})